package api;

import Utils.DBUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplcationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询所有的菜品信息
 */

@WebServlet("/dishlist")
public class DishListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplcationVariable.RESPONSE_CONTENT_TYPE);
        List<Dish> list=new ArrayList<>();
        //非必传参数（是否下架）
        String isDownStr=req.getParameter("isdown");
        String isDeleteStr=req.getParameter("isdelete");
        Integer isdown=2;
        Integer isdelete=2;
        if(!StrUtil.isBlank(isDeleteStr) && isDeleteStr.equals("0")){
            isdelete=0;
        }
        if(!StrUtil.isBlank(isDownStr) && isDownStr.equals("0")){
            isdown=0;
        }
        Connection connection = DBUtil.getConnection();
        String sql = "select * from dish";
        if (isdown == 0 || isdelete==0) sql += " where isdown=? or isdelete=?";
        PreparedStatement statement = connection.prepareStatement(sql);
         statement.setInt(1, isdown);
         statement.setInt(2,isdelete);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            Dish dish = new Dish();
            dish.setDid(resultSet.getInt("did"));
            dish.setName(resultSet.getString("name"));
            dish.setPrice(resultSet.getBigDecimal("price"));
            dish.setIsdown(resultSet.getInt("isdown"));
            dish.setCreatetime(resultSet.getString("createtime"));
            dish.setSelect(false);
            list.add(dish);
        }

        DBUtil.close(resultSet,statement,connection);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(200,list,"")));
    }
}
